#include "XScreenRecord.h"
#include "XCaptureThread.h"
#include "XTAudioThread.h"
#include "XVideoWriter.h"
#include <iostream>
#include <QDebug>
using namespace std;
bool XScreenRecord::Start(const char* filename)
{
	if (!filename)return false;
	Stop();
	mutex.lock();
	isExit = false;

	//初始化屏幕录制
	XCaptureThread::Get()->fps = fps;
	XCaptureThread::Get()->Start();

	//初始化音频录制
	isAudioRecordEnable = XTAudioThread::Get()->Start();

	//初始化编码器
	XVideoWriter::Get()->inWidth = XCaptureThread::Get()->width;
	XVideoWriter::Get()->inHeight = XCaptureThread::Get()->height;
	qDebug() << "输入的宽=" << XVideoWriter::Get()->inWidth;
	qDebug() << "输入的高=" << XVideoWriter::Get()->inHeight;
	XVideoWriter::Get()->outWidth = outWidth;
	XVideoWriter::Get()->outHeight = outHeight;
	XVideoWriter::Get()->outFPS = fps;
	XVideoWriter::Get()->Init(filename);
	XVideoWriter::Get()->AddVideoStream();
	if (isAudioRecordEnable) {
		XVideoWriter::Get()->AddAudioStream();
	}
	if (!XVideoWriter::Get()->WriteHead())
	{
		mutex.unlock();
		Stop();
		return false;
	}

	mutex.unlock();
	start();
	return true;
}
void XScreenRecord::Stop()
{
	mutex.lock();
	isExit = true;
	mutex.unlock();
	wait();
	mutex.lock();
	XVideoWriter::Get()->WriteEnd();
	XVideoWriter::Get()->Close();
	XCaptureThread::Get()->Stop();
	if (isAudioRecordEnable) {
		XTAudioThread::Get()->Stop();
	}
	mutex.unlock();
}
void XScreenRecord::run()
{


	while (!isExit)
	{
		mutex.lock();

		//写入视频
		char* rgb = XCaptureThread::Get()->GetRGB();
		if (rgb)
		{
			AVPacket* p = XVideoWriter::Get()->EncodeVideo((unsigned char*)rgb);
			delete rgb;
			XVideoWriter::Get()->WriteFrame(p);
			qDebug() << "@";
		}
		if (isAudioRecordEnable) {
			//写入音频
			char* pcm = XTAudioThread::Get()->GetPCM();
			if (pcm)
			{
				AVPacket* p = XVideoWriter::Get()->EncodeAudio((unsigned char*)pcm);
				delete pcm;
				XVideoWriter::Get()->WriteFrame(p);
				qDebug() << "#";
			}
		}
		msleep(10);
		mutex.unlock();
	}
}

XScreenRecord::XScreenRecord()
{
}


XScreenRecord::~XScreenRecord()
{
}
